<template>
	<scroll-view class="danmaku-container" :scroll-y='true' :scroll-into-view="autoScroll ? lastDanmuId : ''"
		@scroll="onScroll">
		<text class="danmaku-item" v-for="(msg, index) in messages" :id="'danmu-' + index">
			{{ msg }}
		</text>
	</scroll-view>
</template>

<script setup>
	import {
		ref,
		computed,
		nextTick
	} from 'vue'

	const messages = ref([])
	
	let lastDanmuId = ''
	
	// 滚动监听，判断是否手动滚动
	const autoScroll = ref(true)
	let programmaticScroll = false
	let scrollTimer = null
	let pTimer = null

	function addDanmaku(text) {
		console.log(lastDanmuId)
		messages.value.push(text)
		// 延迟设置 scroll-into-view 才能避免闪一下顶部
		// if (autoScroll.value) {
			console.log("延迟")
			programmaticScroll = true
			clearTimeout(pTimer)
			// nextTick(() => {
				pTimer = setTimeout(() => {
					programmaticScroll = false
					console.log(messages.value.length)
					lastDanmuId ='danmu-' + (messages.value.length - 1)
					 onProgrammaticScroll()
				}, 50) // 延迟触发滚动逻辑，确保 DOM 完成挂载
			// })
		// }
	}
	
	function onProgrammaticScroll() {
		if (programmaticScroll) {
			console.log("触发滚动->跳过#1")
			return
		}
		console.log("触发滚动#1", autoScroll.value, lastDanmuId)
		
		autoScroll.value = false
		clearTimeout(scrollTimer)
		scrollTimer = setTimeout(() => {
			autoScroll.value = true
		}, 100)
	}
	
	function onScroll() {
		if (programmaticScroll) {
			console.log("触发滚动->跳过")
			return
		}
		console.log("触发滚动", autoScroll.value, lastDanmuId)
		// if (autoScroll.value) {
			autoScroll.value = false
					// 用户停止滚动 2 秒后，重新开启自动滚动
					clearTimeout(scrollTimer)
					scrollTimer = setTimeout(() => {
						autoScroll.value = true
					}, 2000)
		// }else{
		// 	if (scrollTimer == null) {
		// 		autoScroll.value = true
		// 		onScroll()
		// 	}
		// 	console.error("触发滚动错误", autoScroll.value, lastDanmuId.value)
		// }

	}
	// 暴露方法给父组件调用
	defineExpose({
		addDanmaku
	})
</script>

<style scoped>
	.danmaku-container {
		position: absolute;
		bottom: 110rpx;
		left: 0rpx;
		width: 740rpx;
		/* padding: 20rpx; */
		opacity: 0.8;
		display: flex;
		flex-direction: column;
		max-height: 300rpx;
		/* 限制高度区域 */
		overflow-y: scroll;
		/* padding-bottom: 10rpx; */
	}
	.danmaku-item {
		background: rgba(0, 0, 0, 0.2);	
		color: #cbcb00;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		font-size: 0.8em;
		margin-bottom: 6rpx;
		align-self: flex-start;   /* 不拉满整行，宽度自适应 */
		align-items: center;     /* 垂直居中 */
	}
</style>